<template>
  <PageWrapper dense>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <RadioGroup v-model:value="queryStatus">
          <RadioButton value="0">所有的</RadioButton>
          <RadioButton value="1">我的</RadioButton>
          <RadioButton value="2">我关注的</RadioButton>
          <RadioButton value="3">我下属的</RadioButton>
        </RadioGroup>
        <a-button
          @click="downloadExcel(exportCustomer, '客户数据')"
          v-auth="'customer:customer:export'"
          >导出</a-button
        >
        <a-button type="primary" @click="handleAdd" v-auth="'demo:demo:add'">新增</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'customerName'">
          <a-button type="link" size="small" @click="handleDetail(record)">{{
            record.customerName
          }}</a-button>
        </template>
        <template v-if="column.dataIndex === 'customerLabel'">
          <Space :size="2">
            <Tag v-for="item in record.customerLabel.split(',')" :key="item" color="green">{{
              item
            }}</Tag>
          </Space>
        </template>
        <template v-if="column.key === 'action'">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                label: '修改',
                icon: IconEnum.EDIT,
                type: 'primary',
                ghost: true,
                auth: 'customer:customer:edit',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: record.followStatus ? '取消关注' : '关注',
                icon: record.followStatus ? IconEnum.UNLOCK : IconEnum.LOCK,
                type: 'primary',
                ghost: true,
                ifShow: true,
                onClick: handleFollow.bind(null, record),
              },
              {
                label: '删除',
                icon: IconEnum.DELETE,
                type: 'primary',
                danger: true,
                ghost: true,
                auth: 'customer:customer:remove',
                popConfirm: {
                  placement: 'left',
                  title: '是否删除客户[' + record.customerName + ']?',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
  </PageWrapper>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue';
  import { downloadExcel } from '@/utils/file/download';
  import { Tag, Space, RadioGroup, RadioButton } from 'ant-design-vue';
  import { PageWrapper } from '@/components/Page';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { listCustomer, delCustomer, updateCustomerFllow, exportCustomer } from '@/api/customer';
  import { useGo } from '@/hooks/web/usePage';
  import { formSchems, columns } from './customer.data';
  import { IconEnum } from '@/enums/appEnum';
  import { PageEnum } from '@/enums/pageEnum';
  import { useUserStoreWithOut } from '@/store/modules/user';
  defineOptions({ name: 'Customer' });
  const queryStatus = ref<string>('0');
  const userStore = useUserStoreWithOut();
  const [registerTable, { reload }] = useTable({
    title: '客户列表',
    api: listCustomer,
    showIndexColumn: false,
    rowKey: 'id',
    useSearchForm: true,
    formConfig: {
      schemas: formSchems,
      baseColProps: {
        span: 6,
      },
    },
    beforeFetch: (params: Recordable) => {
      params.queryStatus = queryStatus.value;
      if (params.dateRange) {
        params.beignTime = params.dateRange[0];
        params.endTime = params.dateRange[1];
        delete params.dateRange;
      }
      return params;
    },
    afterFetch(data: Recordable[]) {
      const newData = data.map((item) => {
        return {
          ...item,
          followStatus: item.followerIds
            ? item.followerIds.split(',').findIndex((item) => item == userStore.userInfo?.userId) >
              -1
            : false,
        };
      });
      return newData;
    },
    columns: columns,
    actionColumn: {
      width: 260,
      title: '操作',
      key: 'action',
      fixed: 'right',
    },
  });
  watch(
    () => queryStatus.value,
    () => {
      reload();
    },
  );
  const go = useGo();
  function handleDetail(record: Recordable) {
    go({ path: '/customer/customerDetail' as PageEnum, query: { id: record.customerId } });
  }
  function handleEdit(record: Recordable) {
    go({
      path: '/customer/customerEdit' as PageEnum,
      query: { id: record.customerId, type: 'update' },
    });
  }

  function handleAdd() {
    go({ path: '/customer/customerEdit' as PageEnum, query: { type: 'add' } });
  }

  async function handleFollow(record: Recordable) {
    let followerIds = <string | number | undefined>'';
    if (record.followStatus) {
      followerIds = record.followerIds
        .split(',')
        .filter((item: any) => item != userStore.userInfo?.userId)
        .join(',');
    } else {
      followerIds = record.followerIds + ',' + userStore.userInfo?.userId;
    }
    await updateCustomerFllow(record.customerId, followerIds);
    await reload();
  }

  async function handleDelete(record: Recordable) {
    await delCustomer(record.customerId);
    await reload();
  }
</script>

<style scoped></style>
